﻿using System;
using UnityEngine;

#if UNITY_ANDROID
/// <summary>
/// 读取android安装包内的文件
/// </summary>
public class AndroidAssets
{
    public static bool ObbExists()
    {
#if USE_OBB && !UNITY_EDITOR
        IGooglePlayObbDownloader obbDownloader = GooglePlayObbDownloadManager.GetGooglePlayObbDownloader();
        return obbDownloader.GetMainOBBPath() != null;
#else
        return true;
#endif
    }

    public static void InitObb(int mainVersion, int patchVersion)
    {
#if USE_OBB && !UNITY_EDITOR
        var jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        var jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
        jo.Call("initObb", mainVersion, patchVersion);
#endif
    }

    // 获取文件流
    static AndroidJavaObject GetStream(string path)
    {
        try
        {
            var jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            var jo = jc.GetStatic<AndroidJavaObject>("currentActivity");
#if USE_OBB && !UNITY_EDITOR
        return jo.Call<AndroidJavaObject>("openFileFromObb", path);
#else
            return jo.Call<AndroidJavaObject>("getAssets")
                    .Call<AndroidJavaObject>("open", path);
#endif
        }
        catch(Exception)
        {

            return null;
        }
    }

    /// <summary>
    /// 判断文件是否存在
    /// </summary>
    public static bool FileExists(string path)
    {
        AndroidJavaObject stream = GetStream(path);
        if (stream == null)
        {
            //Debug.LogErrorFormat("AndroidAssets {0} not exist!", path);
            return false;
        }

        stream.Call("close");
        return true;
    }

    /// <summary>
    /// 获取文件大小
    /// </summary>
    public static long GetFileSize(string path)
    {
        var stream = GetStream(path);
        if (stream == null)
            return 0;

        int size = stream.Call<int>("available");
        stream.Call("close");
        return size;
    }

    /// <summary>
    /// 读取文件二进制数据
    /// </summary>
    public static byte[] ReadAllBytes(string path)
    {
        var stream = GetStream(path);
        if (stream == null)
            return null;

        IntPtr array = AndroidJNI.NewByteArray(stream.Call<int>("available"));
        var cls = new AndroidJavaClass("java.io.InputStream"); ;
        var clsPtr = cls.GetRawClass();
        var methodRead = AndroidJNIHelper.GetMethodID(clsPtr, "read", "([B)I");
        AndroidJNI.CallIntMethod(stream.GetRawObject(), methodRead, new[] { new jvalue() { l = array } });
        var bytes = AndroidJNI.FromByteArray(array);
        AndroidJNI.DeleteLocalRef(array);
        stream.Call("close");
        return bytes;
    }
}
#endif